package com.du.cloud.service.admin.service.impl;

import com.du.cloud.common.base.constant.enums.MenuType;
import com.du.cloud.service.admin.api.model.dto.SysUserDTO;
import com.du.cloud.service.admin.api.model.dto.UserInfo;
import com.du.cloud.service.admin.api.model.entity.SysRole;
import com.du.cloud.service.admin.api.model.entity.SysRule;
import com.du.cloud.service.admin.mapper.SysUserMapper;
import com.du.cloud.service.admin.service.SysRoleService;
import com.du.cloud.service.admin.service.SysRuleService;
import com.du.cloud.service.admin.service.SysUserService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * Desc:
 * Author: dushuang
 * Date: 2020/5/25
 **/
@Service
public class SysUserServiceImpl implements SysUserService {

    @Resource
    private SysUserMapper sysUserMapper;
    @Resource
    private SysRoleService sysRoleService;
    @Resource
    private SysRuleService sysRuleService;

    @Override
    public SysUserDTO findByUsername(String username) {
        return sysUserMapper.findByUsername(username);
    }

    @Override
    public SysUserDTO findUserById(Integer userId) {
        return sysUserMapper.findUserById(userId);
    }

    @Override
    public UserInfo info(SysUserDTO user) {
        UserInfo userInfo = new UserInfo();
        // 用户信息
        userInfo.setUser(user);
        Integer userId = user.getId();
        // 角色信息
        List<SysRole> userRole = sysRoleService.findUserRole(userId);
        if (userRole.size() > 0) {
            List<String> roles = userRole.stream()
                    .map(SysRole::getRoleCode)
                    .collect(Collectors.toList());
            userInfo.setRoles(roles);
        }
        // 权限信息
        List<SysRule> userRule = sysRuleService.findUserRule(userId);
        if (userRule.size() > 0) {
            Set<String> menus = new HashSet<>();
            Set<String> permissions = new HashSet<>();
            userRule.forEach(i -> {
                MenuType menuType = MenuType.getMenuType(i.getRuleType());
                if (menuType != null) {
                    switch (menuType) {
                        case MENU:
                            menus.add(i.getRuleCode());
                            break;
                        case PERMISSION:
                            permissions.add(i.getRuleCode());
                            break;
                    }
                }
            });
            userInfo.setMenus(menus);
            userInfo.setPermissions(permissions);
        }
        return userInfo;
    }
}
